package com.atguigu.gmall.activity.consumer;

import com.atguigu.gmall.activity.mapper.SeckillGoodsMapper;
import com.atguigu.gmall.activity.redis.CacheHelper;
import com.atguigu.gmall.activity.util.DateUtil;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.rebbit.constant.MqConst;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
public class ActivityConsumer {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;


    //半夜12点接收消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TASK_1, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_TASK),
            key = MqConst.ROUTING_TASK_1
    ))
    public void seckillImportRedis(Message message, Channel channel) {
        try {
            //将秒杀表的数据导入缓存  当天的
            QueryWrapper<SeckillGoods> wrapper = new QueryWrapper<>();
            wrapper.eq("status", 1);
            wrapper.gt("stock_count", 0);
            //日期函数，日期格式的转换
            wrapper.eq("DATE_FORMAT(start_time,'%Y-%m-%d')", DateUtil.formatDate(new Date()));
            //创建当前时间
            // Date time = Calendar.getInstance().getTime();
            //4:添加秒杀
            //从数据库中获取要添加的购物项
            List<SeckillGoods> seckillGoodsList = seckillGoodsMapper.selectList(wrapper);
            //不为空需要添加
            if (!CollectionUtils.isEmpty(seckillGoodsList)) {
                //添加到秒杀
                seckillGoodsList.forEach(seckillGoods -> {
                    //5:将结果集保存到Redis缓存中  （考虑 使用redis五大数据类型中哪个类型）
                    //不存在添加到reddis
                    if (!redisTemplate.opsForHash().hasKey(RedisConst.SECKILL_GOODS,
                            seckillGoods.getSkuId().toString())) {
                        redisTemplate.opsForHash().put(RedisConst.SECKILL_GOODS,
                                seckillGoods.getSkuId().toString(), seckillGoods);
                    }
                    //将剩余数量添加到redis中
                    //6:防止超卖 list
                    redisTemplate.opsForList().leftPushAll(RedisConst.SECKILL_STOCK_PREFIX + seckillGoods.getSkuId()
                            , buildSkuIds(seckillGoods.getSkuId(), seckillGoods.getStockCount()));
                    //7:状态位 每款商品都有自己的状态位
                    //参数1：信道
                    //参数2：消息 skuId:0  skuId:1 两种状态
                    redisTemplate.convertAndSend("seckillpush",
                            seckillGoods.getSkuId() + "1");//商品有货状态
                });
            }

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_SECKILL_USER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_SECKILL_USER),
            key = MqConst.ROUTING_SECKILL_USER
    ))
    public void seckill(UserRecode userRecode, Message message, Channel channel) {
        try {
            //校验状态位
            Object o = CacheHelper.get(userRecode.getSkuId().toString());
            if(!"1".equals(o)){
                return;
            }
            //用户是否来过 如果存在返回0 false  如果没来过 返回1 true
            Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(
                    RedisConst.SECKILL_USER+userRecode.getUserId(), "1");
            if(!aBoolean){
                //来过
                return;
            }
            //获取抢购资格
            String skuId = (String) redisTemplate.opsForList().leftPop(RedisConst.SECKILL_STOCK_PREFIX
                    + userRecode.getSkuId());
            if(skuId==null){
                //更改状态位 每款商品都有自己的状态位
                //参数1：信道
                //参数2：消息 skuId:0  skuId:1 两种状态
                redisTemplate.convertAndSend("seckillpush",
                        userRecode.getSkuId() + "0");//商品有货状态
                return;
            }
            //获取的资格保存到redis中
            redisTemplate.opsForValue().set(RedisConst.SECKILL_ORDERS+userRecode.getUserId(),userRecode.getSkuId().toString());
            //有资格
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String[] buildSkuIds(Long skuId, Integer stock) {
        String[] strings = new String[stock];
        for (Integer integer = 0; integer < stock; integer++) {
            strings[integer] = skuId.toString();
        }
        return strings;
    }


}
